package org.bonorsoft.modules.user.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.java.Log;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.dataquery.DataQueryGenerator;
import org.bonorsoft.common.system.vo.Ztree;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.modules.user.entity.SysDepart;
import org.bonorsoft.modules.user.entity.SysRole;
import org.bonorsoft.modules.user.service.ISysDepartService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 组织结构
 * @Author: WilliamYe
 * @Date:   2020-11-13
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/system/dept")
public class SysDepartController extends BonorController<SysDepart, ISysDepartService> {
	private String prefix = "system/dept";

	@Autowired
	private ISysDepartService sysDepartService;

	@RequiresPermissions("system:dept:view")
	@GetMapping()
	public String dept()
	{
		return prefix + "/dept";
	}

	/**
	 * 分页列表查询
	 *
	 * @param sysDepart
	 * @param req
	 * @return
	 */
	@PostMapping(value = "/list")
	@RequiresPermissions("system:dept:list")
	@PermissionData(value = "single")
	@ResponseBody
	public List<SysDepart> queryPageList(SysDepart sysDepart, HttpServletRequest req){
		QueryWrapper<SysDepart> queryWrapper = DataQueryGenerator.initQueryWrapper(sysDepart, req);
		queryWrapper.orderByAsc("order_num");
		return sysDepartService.list(queryWrapper);

	}

	/**
	 * 新增部门
	 */
	@GetMapping("/add/{parentId}")
	public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
	{
		mmap.put("dept", sysDepartService.getById(parentId));
		return prefix + "/add";
	}

	/**
	 * 选择部门树
	 */
	@GetMapping("/selectDeptTree/{deptId}")
	public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap)
	{
		mmap.put("dept", sysDepartService.getById(deptId));
		return prefix + "/tree";
	}

	/**
	 * 添加
	 *
	 * @param sysDepart
	 * @return
	 */
	@AutoLog(value = "组织结构-添加")
	@RequiresPermissions("system:dept:add")
	@PostMapping(value = "/add")
	@ResponseBody
	public Result<?> add(@Validated SysDepart sysDepart) {
		if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(sysDepartService.checkDeptNameUnique(sysDepart)))
		{
			return Result.error("新增部门'" + sysDepart.getDeptName() + "'失败，部门名称已存在");
		}
		sysDepartService.save(sysDepart);
		return Result.ok("添加成功！");
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{deptId}")
	public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap)
	{
		SysDepart dept = sysDepartService.getById(deptId);
		if (StringUtils.isNotNull(dept) && 100L == deptId)
		{
			mmap.put("parentName", "无");
		}
		String parentName = sysDepartService.getDepartNameById(dept.getParentId()).getDeptName();
		mmap.put("parentName", parentName);
		mmap.put("dept", dept);
		return prefix + "/edit";
	}

	/**
	 * 编辑
	 *
	 * @param sysDepart
	 * @return
	 */
	@AutoLog(value = "组织结构-编辑")
	@RequiresPermissions("system:dept:edit")
	@PostMapping(value = "/edit")
	@ResponseBody
	public Result<?> edit(@Validated SysDepart sysDepart) {
		if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(sysDepartService.checkDeptNameUnique(sysDepart)))
		{
			return Result.error("修改部门'" + sysDepart.getDeptName() + "'失败，部门名称已存在");
		}
		else if (sysDepart.getParentId().equals(sysDepart.getDeptId()))
		{
			return Result.error("修改部门'" + sysDepart.getDeptName() + "'失败，上级部门不能是自己");
		}
		sysDepartService.updateDept(sysDepart);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param deptId
	 * @return
	 */
	@AutoLog(value = "组织结构-通过id删除", operateType = 4)
	@RequiresPermissions("system:dept:remove")
	@DeleteMapping(value = "/remove/{deptId}")
	@ResponseBody
	public Result<?> remove(@PathVariable("deptId") Long deptId) {
		if (sysDepartService.selectDeptCount(deptId) > 0)
		{
			return Result.error("存在下级部门,不允许删除");
		}
		if (sysDepartService.checkDeptExistUser(deptId))
		{
			return Result.error("部门存在用户,不允许删除");
		}
		sysDepartService.removeById(deptId);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "组织结构-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.sysDepartService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "组织结构-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SysDepart sysDepart = sysDepartService.getById(id);
		return Result.ok(sysDepart);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param sysDepart
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, SysDepart sysDepart) {
      return super.exportXls(request, sysDepart, SysDepart.class, "组织结构");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, SysDepart.class);
  }

	/**
	 * 加载部门列表树
	 */
	@GetMapping("/treeData")
	@ResponseBody
	@PermissionData(value = "single")
	public List<Ztree> treeData(HttpServletRequest req)
	{
		List<Ztree> ztrees = sysDepartService.selectDeptTree(new SysDepart(), req);
		return ztrees;
	}

	/**
	 * 加载角色部门（数据权限）列表树
	 */
	@GetMapping("/roleDeptTreeData")
	@ResponseBody
	public List<Ztree> deptTreeData(SysRole role, HttpServletRequest request)
	{
		List<Ztree> ztrees = sysDepartService.roleDeptTreeData(role, request);
		return ztrees;
	}

	/**
	 * 校验部门名称
	 */
	@PostMapping("/checkDeptNameUnique")
	@ResponseBody
	public String checkDeptNameUnique(SysDepart dept)
	{
		return sysDepartService.checkDeptNameUnique(dept);
	}

}
